import React,{useState,useEffect} from 'react'
import {Form,Input,Button,Card,message,Upload,Icon}from 'antd';
import{createApi,getOneById,modifyOne}from '../../../server/products';
import{serverUrl}from '../../../utils/config';
// 引入编辑器组件
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'
function Edit(props) {
  //修改那一栏的返回的数据用useState存起来
  const[currentData,setCurrentData]=useState({})
  // console.log('Edit页面的参数',props)
  
    //表单验证
    const{getFieldDecorator}=props.form;
    //自定义校验规则
    const priceValidate=(rule,value,callback)=>{
        if(value*1>100){
          alert('kkkkkk')
            callback('价格不能大于100')
        }else{
            callback();
        }
    }
  //该页面初始化时执行useEffect
   useEffect(()=>{
   //判断其点击来是新增还是修改 若是修改则调用请求函数getOneById() 
  if(props.match.params.id){
    getOneById(props.match.params.id).then(res=>{
      console.log('getOneById获取每一栏的数据',res)
      setCurrentData(res)
      setImageUrl(res.coverImg)
      setEditorState(BraftEditor.createEditorState(res.content))

    })
}
   },[])
    //表单验证
    const handleSubmit = e => {
        console.log(e)
        e.preventDefault();
        props.form.validateFieldsAndScroll((err, values) => {
          // console.log('商品编辑的名称以及价格',values)
          //   createApi(values).then(res=>{
          //     console.log('通过createApi请求到的数据',res);
          //     props.history.push('/admin/products');
          //   })
          if (!err) {
            console.log('提交');
            
           //判断其是新增还是说编辑已有的内容
           if(props.match.params.id){
           modifyOne(props.match.params.id,{...values,coverImg:imageUrl,content:editorState.toHTML()}).then(res=>{
             console.log('编辑后的内容',res)
             props.history.push('/admin/products')
           }).catch(err=>{
             console.log('error',err);
           })
           }else{
           createApi({...values,coverImg:imageUrl,content:editorState.toHTML()}).then(res=>{
                console.log('新增栏的数据',res);
                props.history.push('/admin/products')
              }).catch(err=>{
                console.log('新增栏的error',err);
              })
           }
           
          }else{
              message.error('请输入正确的内容')
          }
        });
      };
// -------------------------------文件上传与下载--------------------------------- 
const[imageUrl,setImageUrl]=useState('');
const[loading,setLoading]=useState(false);
const handleChange = info => {
  if (info.file.status === 'uploading') {
    // this.setState({ loading: true });
    setLoading(true)
    return;
  }
  if (info.file.status === 'done') {//上传完成
    // Get this url from response in real world.
    setLoading(false);
    console.log('上传完成的info',info);
    setImageUrl(info.file.response.info)
  } 
}
const uploadButton = (
  <div>
    <Icon type={loading ? 'loading' : 'plus'} />
    <div className="ant-upload-text">Upload</div>
  </div>
);
 // 创建一个空的editorState作为初始值
 const[ editorState,setEditorState]=useState(BraftEditor.createEditorState(null));
//富文本编辑区域发生改变的时候
   const handleEditorChange=(e)=>{
      // this.state.editorState.toHTML()
       setEditorState(e)
   }
     return (
        <>
        <Card title="商品编辑">
        <Form onSubmit={e=>handleSubmit(e)}>
        <Form.Item label="名字">
          {getFieldDecorator("name", {
            rules: [
              {
                required: true,
                message: "请输入商品名字"
              },
              //自定义校验规则
              {
                  validator:priceValidate
              }
            ],
            initialValue:currentData.name
            
          })(<Input placeholder="请输入商品名字" />)}
        </Form.Item>
        <Form.Item label="价格">
          {getFieldDecorator("price", {
            rules: [
              {
                required: true,
                message: "请输入商品价格"
              }
            ],
            initialValue:currentData.price
          })(<Input placeholder="请输入商品价格" />)}
        </Form.Item>
            <Form.Item>
            <Button htmlType="submit" type="primary">保存</Button>
            </Form.Item>
        </Form>   
        {/* 文件选择上传和拖拽上传控件。 */}
        <Upload
        name="file"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={serverUrl+'/api/v1/common/file_upload'}
        onChange={info=>handleChange(info)}
      >
        {imageUrl ? <img src={serverUrl+imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
        </Card>
        <BraftEditor
                    value={editorState}
                    onChange={e=>handleEditorChange(e)}
                />
        </>
    )
}

// export default Form.create({name:'productEdit'})(Edit);
export default Form.create({ name: "productEdit" })(Edit);
